package com.yao.sys.service.impl;

import cn.hutool.core.lang.Console;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.enums.SysErrorEnum;
import com.yao.common.exception.BusinessException;
import com.yao.sys.entity.AccountEntity;
import com.yao.sys.entity.dto.AccountDto;
import com.yao.sys.entity.dto.UserDto;
import com.yao.sys.mapper.UserMapper;
import com.yao.sys.service.AccountService;
import com.yao.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表 接口实现
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2020-03-23
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDto> implements UserService {

    @Autowired
    private UserMapper mapper;

    @Autowired
    private AccountService accountService;

    @Override
//    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public void add(UserDto dto) {

        LambdaQueryWrapper<AccountDto> accountWrapper = Wrappers.lambdaQuery();
        accountWrapper.eq(AccountEntity::getPhone, dto.getPhone());
        AccountDto account = accountService.getOne(accountWrapper);

        // MD5加密password
        String encryptPwd = SecureUtil.md5(dto.getPassword());

        // 创建账户
        if (null == account) {

            account.setAccountName(dto.getUserName())
                    .setName(dto.getUserName()).setPassword(encryptPwd).setPhone(dto.getPhone()).setOperator(-1);

            boolean saveRst = accountService.save(account);
            Console.log("创建账户成功吗？ ::: {}", saveRst);

            if (!saveRst) {
                throw new BusinessException("创建账户失败啦.");
            }
        }

        // 创建用户
        dto.setAccountId(account.getId());
        dto.setPassword(encryptPwd);
        dto.setSort(1);
        this.save(dto);
    }

    @Override
//    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public boolean modifyById(UserDto dto) {
        return this.updateById(dto);
    }

    @Override
//    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public boolean deleteById(Integer id) {

        return this.removeById(id);
    }

    @Override
    public IPage<UserDto> listpage(Page page) {
        IPage<UserDto> iPage = mapper.listpage(page);

        List<UserDto> collect = iPage.getRecords().stream().map(e -> e.fill()).collect(Collectors.toList());
        iPage.setRecords(collect);

        return iPage;
    }

    @Override
    public boolean login(UserDto dto) {

        // 根据用户名查询用户对象
        LambdaQueryWrapper<UserDto> queryWrapper =
            Wrappers.lambdaQuery();
        queryWrapper.eq(UserDto::getUserName, dto.getUserName());

        UserDto user = this.getOne(queryWrapper);

        // 比对密码
        String encryptPwd = SecureUtil.md5(dto.getPassword());

        if (null == user || !user.getPassword().equals(encryptPwd)) {
            throw new BusinessException(SysErrorEnum.ERROR.getErrCode(), "用户[{}]登陆失败，请检查用户名和密码", dto.getUserName());
        }

        log.info("用户[{}]登陆成功", dto.getUserName());
        return true;

    }

    @Override
    public UserDto byId(Integer id) {

        return mapper.byId(id);
    }
}